import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store';  // 纯js文件不能使用 this.$store ,所以这里直接引入了store对象，调用方式和this.$store是一样的



Vue.use(VueRouter)

  const routes = [
  {
    path: '/',
    redirect:'/main' // 根路由跳转到main 这里没有component
  },
  {
    path: '/main',
    redirect:'/main/home',  // main又跳转到 main/home 注意这里有component，目的是为了让他的子路由下的页面都能基于Main组件显示 （有公用的tabbar组件）
    component: () => import(/* webpackChunkName: "main" */ '../views/Main.vue'),
    children:[
      {
        path: 'Home',
        name: 'Home',
        component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
      }, 
      {
        path: 'life',
        name: 'Life',
        component: () => import(/* webpackChunkName: "life" */ '../views/Life.vue')
      },  {
        path: 'my',
        name: 'My',
        meta:{
          needLogin:true
        },
        component: () => import(/* webpackChunkName: "my" */ '../views/My.vue')
      }
    ]
  },
  {
    path: '/invest',
    name: 'Invest',
    component: () => import(/* webpackChunkName: "invest" */ '../views/Invest.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue')
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import(/* webpackChunkName: "detail" */ '../views/Detail.vue')
  },
  
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from ,next)=>{
  console.log(to);
    // 如果要访问的页面有meta属性，且meta属性理的含有needLogin属性且值为true 就需要做登录判断
   if(to.meta && to.meta.needLogin){
     if(store.state.token){ // 判断如果token不为空 就继续
       next();
     }else{ 
         // 如果token为空就跳转到登录页
       router.push('/login')
     }
   }else{ // 如果不需要登录 ，就直接继续
     next();
   }
})
export default router
